<?php
namespace Admin\Controller;
use Think\Controller;
use Think\Page;
class SmsportController extends CommonController {
    public function config(){
        $port_object = D('sms_config');
        if (IS_POST) {
            $data = $port_object->create();
            if ($data) {
                $rs = $port_object->save($data);
                if ($rs) {
                    $ajax = array(
                      'status'=>1,
                      'text'=>'短信接口配置保存成功',
                      'url'=>U('config')
                    );
                } else {
                    $ajax = array(
                      'status'=>0,
                      'text'=>'短信接口配置保存失败',
                      'url'=>''
                    );
                }
            }else {
                $ajax = array(
                  'status'=>0,
                  'text'=>$port_object->getError(),
                  'url'=>''
                );
            }
            $this->ajaxReturn($ajax);
        }else {
            $this->assign('mark','extend');
            $this->assign('umark','smsconfig');

            $form_data = $port_object->find(1);

            A('form')->setMetaTitle('短信接口配置')
            ->setBreadCrumb(array('扩展','短信接口','短信接口配置'))
            ->setPostUrl(U('config'))
            ->addFormItem('id','hidden')
            ->addFormItem('appid','text','APPID','',array(),array('required'=>true))
            ->addFormItem('appkey','text','APPKEY','',array(),array('required'=>true))
            ->addFormItem('templet','text','模板ID','模板ID，多个以英文逗号,隔开')
            ->setFormData($form_data)
            ->fetch();
        }
    }
    //列表
    public function index(){
      $templet_object = D('sms_templet');
      $map['status'] = array('egt', '0'); // 禁用和正常状态
      $Page = new Page($templet_object->where($map)->count(),C('ADMIN_CONFIG.page_size'));
      $Page->setConfig('prev','«');
      $Page->setConfig('next','»');
      $data_list     = $templet_object
          ->where($map)
          ->order('id asc')
          ->limit($Page->firstRow.','.$Page->listRows)
          ->select();
      $this->assign('mark','extend');
      $this->assign('umark','smstemp');
      A('list')->setMetaTitle('短信模板列表')
          ->setBreadCrumb(array('扩展','短信接口','短信模板'))
          ->addTopButton('custom',array('title'=>'<i class="icon icon-refresh"></i> 更新模板 ','class'=>'btn btn-primary temp-update','href'=>U('smsport/tempUpdate')))
          ->addTableColumn('id','ID','number',50)
          ->addTableColumn('tid','模板ID','number',80)
          ->addTableColumn('text','模板内容','text','auto','false')
          ->addTableColumn('reply','审批信息','text','auto','false')
          ->addTableColumn('type','模板类型','smstype',90)
          ->addTableColumn('status','审核状态','smsstatus',90)
          ->addTableColumn('','操作','rightbtn',80,'false')
          ->addRightButton('custom',array('title'=>'<i class="icon icon-eye-open"></i> 查看','class'=>'btn btn-primary btn-xs temp-show','href'=>U('smsport/tempShow',array('ids'=>'__dataid__'))))
          ->setTableDataList($data_list)
          ->setTableDataPage($Page->show())
          ->addRightButton('show')
          ->fetch();
    }
    //更新模板
    public function tempUpdate(){
        if(IS_GET){
            $sms_object = D('sms_config');
            $sms_data = $sms_object->find(1);
            $temparr = explode(',',$sms_data['templet']);
            $sms_data['random'] = randoms(8,'number');
            $sms_data['time'] = time();

            $url = 'https://yun.tim.qq.com/v5/tlssmssvr/get_template?sdkappid='.$sms_data['appid'].'&random='.$sms_data['random'];
            $post_data = array(
              'time'=>$sms_data['time'],
              'tpl_id'=>$sms_data['templet'],
              'sig'=>hash('sha256','appkey='.$sms_data['appkey'].'&random='.$sms_data['random'].'&time='.$sms_data['time'],'')
            );
            $res = $this->request_post($url,json_encode($post_data));
            $temps = object_array(json_decode($res));
            $this->addTemplet($temps['data']);
        }
    }
    public function addTemplet($data){
        foreach ($data as $key => $value) {
            $re = M('sms_templet')->where(array('tid'=>$value['id']))->find();
            $t['tid'] = $value['id'];
            $t['text'] = $value['text'];
            $t['status'] = $value['status'];
            $t['type'] = $value['type'];
            $t['reply'] = $value['reply'];
            if ($re) {
                M('sms_templet')->where(array('tid'=>$value['id']))->save($t);
            }else {
                M('sms_templet')->add($t);
            }
        }
    }
    public function request_post($url = '', $param = '') {
        if (empty($url) || empty($param)) {
            return false;
        }
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        $ret = curl_exec($ch);//运行curl
        if (false == $ret) {
            // curl_exec failed
            $result = "{ \"result\":" . -2 . ",\"errmsg\":\"" . curl_error($ch) . "\"}";
        } else {
            $rsp = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if (200 != $rsp) {
                $result = "{ \"result\":" . -1 . ",\"errmsg\":\"". $rsp . " " . curl_error($ch) ."\"}";
            } else {
                $result = $ret;
            }
        }
        curl_close($ch);
        return $result;
    }
}
